package com.sc.nft.util;

import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.sup.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpUtil {
  public static Map<String, Object> getFormData(HttpServletRequest request) {
    StringBuilder sb;
    try {
      BufferedReader streamReader =
          new BufferedReader(
              new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
      String inputStr;
      sb = new StringBuilder();
      while ((inputStr = streamReader.readLine()) != null) {
        sb.append(inputStr);
      }
    } catch (IOException e) {
      log.error("转化HttpServletRequest出错: ", e);
      throw new GlobalRunTimeException(ErrorCode.SYS_ERROR);
    }
    if (sb.length() == 0) {
      log.error("参数为空");
      throw new GlobalRunTimeException(ErrorCode.SYS_ERROR);
    }
    String param = sb.toString();
    Map<String, Object> result = new HashMap<>();
    String[] array = param.split("&");
    for (String string : array) {
      String[] values = string.split("=");
      if (values.length == 2) {
        result.put(values[0], values[1]);
      }
    }
    return result;
  }
}
